import Vue from "vue";
import Vuex, { createLogger } from "vuex";
import MUTATIONTYPES from "./mutation-types";
import module from "./module";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 999,
    todos: [
      { id: 1, text: "...", done: true },
      { id: 2, text: "...", done: false },
    ],
  },
  getters: {
    doneTodos(state) {
      // 根状态，包含模块的局部状态
      console.log(state);
      return state.todos.filter((todo) => todo.done);
    },
    doneTodosCount(state, getters) {
      return getters.doneTodos.length;
    },
    getTodoById(state) {
      return (id: number) => {
        return state.todos.find((todo) => todo.id === id);
      };
    },
  },
  // mutations 中的操作必须是同步操作，devtool 工具是在 mutations 中追踪状态变化的
  // 如果存在异步操作，将会导致状态追踪失效
  mutations: {
    addCount(state, payload) {
      state.count += payload.num;
    },
    [MUTATIONTYPES.ADD_COUNT_MUTATION](state, payload) {
      state.count += payload.num;
    },
  },
  // actions 内部允许异步操作
  actions: {
    addCountAction(context, payload) {
      setTimeout(() => {
        context.commit({
          type: "addCount",
          num: payload.num,
        });
      }, 2000);
    },
  },
  modules: {
    module,
  },
  plugins: [createLogger()],
});

console.log(store);

export default store;
